import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:test_module/BusinessPage.dart';
import 'package:test_module/MyFlutterBinding.dart';
import 'package:test_module/SettingPage.dart';

void main() {
  ///这里的CustomFlutterBinding调用务必不可缺少，用于控制Boost状态的resume和pause
  MyFlutterBinding();
  print("CustomFlutterBinding main defaultRouteName${window.defaultRouteName}");
  runApp(YouthApp());
}

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    print(
        "CustomFlutterBinding build defaultRouteName${window.defaultRouteName}");
    var args = ModalRoute.of(context)?.settings.arguments.toString();
    debugPrint("args $args");
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      ),
      routes: {
        "custom_page": (context) => const SettingPage(text: "ffff"),
        "business_page": (context) => const BusinessPage(),
      },
      home: const MyHomePage(title: 'Flutter Demo Home Pag11e'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //平台通道––––跳转到Android页面
  static const platform = MethodChannel("samples.flutter.jumpto.android");

  @override
  void initState() {
    super.initState();
    platform.setMethodCallHandler(nativeCallHandler);
  }

  // 注册方法，等待被原生通过invokeMethod唤起
  Future<dynamic> nativeCallHandler(MethodCall methodCall) async {
    print("nativeCallHandler------ ${methodCall.method}");
    switch (methodCall.method) {
      case "getFlutterResult":
        //获取参数
        String paramsFromNative = await methodCall.arguments["invokeKey"];
        print("原生android传递过来的参数为------ $paramsFromNative");
        Navigator.pushAndRemoveUntil(context,
            MaterialPageRoute(builder: (context) {
          return const BusinessPage();
        }), (route) => route == null);

        return "你好，这个是从flutter传递过来的数据1";
        break;
      case "onActivityResult":
        //获取参数
        String message = await methodCall.arguments["message"];
        print("原生android传递过来的参数为------ $message");
        return "你好，这个是从flutter传递过来的数据2";
        break;
    }
  }

  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    print(
        "CustomFlutterBinding _MyHomePageState build defaultRouteName${window.defaultRouteName}");

    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            TextButton(
                onPressed: _jumpToAndroidMethod,
                child: const Text('跳转到Android页面'))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Future<void> _jumpToAndroidMethod() async {
    final String result = await platform.invokeMethod('jumpToAndroidPage');
    debugPrint('result===$result');
  }
}

// flutter_boost
class YouthApp extends StatefulWidget {
  const YouthApp({Key? key}) : super(key: key);

  @override
  State<YouthApp> createState() => _YouthAppState();
}

class _YouthAppState extends State<YouthApp> {
  Map<String, FlutterBoostRouteFactory> routerMap = {
    '/': (settings, uniqueId) {
      return MaterialPageRoute(
          settings: settings,
          builder: (_) {
            return const Center(
              child: Text('data'),
            );
          });
    },
    'customPage': (settings, uniqueId) {
      return MaterialPageRoute(
          settings: settings,
          builder: (_) {
            Map<String, dynamic> map = settings.arguments as Map<String, dynamic>;
            String data = map['data'] as String;
            return SettingPage(text: "ffff");
          });
    },
    'businessPage': (settings, uniqueId) {
      return MaterialPageRoute(
          settings: settings,
          builder: (_) {
            Map<String, dynamic> map = settings.arguments as Map<String, dynamic>;
            String data = map['data'] as String;
            return BusinessPage();
          });
    }
  };

  Route<dynamic>? routeFactory(RouteSettings settings, String? uniqueId) {
    FlutterBoostRouteFactory func =
        routerMap[settings.name] as FlutterBoostRouteFactory;
    return func(settings, uniqueId);
  }

  Widget appBuilder(Widget home) {
    return MaterialApp(
      home: home,
      debugShowCheckedModeBanner: true,

      ///必须加上builder参数，否则showDialog等会出问题
      builder: (_, __) {
        return home;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return FlutterBoostApp(
      routeFactory,
      appBuilder: appBuilder,
    );
  }
}
